package sicnu.cs.ich.es.config;

import lombok.Data;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * ES配置类,配合logstash（每分钟更新一次）
 * 来实现es和数据库信息增量更新同步
 * @author 沈洋 邮箱:1845973183@qq.com
 * @create 2021/11/29-20:36
 **/
@Data
@Configuration
@ConfigurationProperties(prefix = "ich.es")
public class ElasticSearchConfig {

    private String host = "relosy.cn";
    private Integer port = 9200;
    private String scheme = "http";
    private String username = "elastic";
    private String password = "123456";
    //@Bean
    //public RestHighLevelClient restHighLevelClient(){
    //    // 集群就配置多个HttpHost即可
    //    return new RestHighLevelClient(
    //            RestClient.builder(new HttpHost(ES_HOST,ES_PORT,ES_SCHEME)));
    //}

    //通用设置项
    public static final RequestOptions COMMON_OPTIONS;

    static {
        RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
        COMMON_OPTIONS = builder.build();
    }

    @Bean
    public RestHighLevelClient esRestClient() {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                //es账号密码
                new UsernamePasswordCredentials(username, password));

        return new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost(host, port, scheme)
                ).setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                    @Override
                    public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                        httpClientBuilder.disableAuthCaching();
                        return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                    }
                })
        );
    }

}
